package cn.idu.socket.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class UDPClientDemo01 {
    public static void main(String[] args) throws Exception {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    openUDPServer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.sleep(1000);
        //建立socket
        DatagramSocket socket = new DatagramSocket();
        //发送目标
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 9090);
        //建个包
        byte[] data = "hello".getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(data, data.length, inetSocketAddress);
        //发送包
        socket.send(packet);
        //关闭socket
        socket.close();
    }

    public static void openUDPServer() throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);//阻塞接收
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(), 0, packet.getData().length));
        socket.close();
    }
}
